/**
 * 395. 至少有 K 个重复字符的最长子串
 * https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters/
 */

/**
 * @param {string} s
 * @param {number} k
 * @return {number}
 */
function longestSubstring(s, k) {
  if (k <= 1) {
    return s.length;
  }
  const codeA = 'a'.charCodeAt(0);
  const totalCharCount = new Set(s).size;
  let max = 0;
  const cache = new Array(26);
  for (let maxCount = 1; maxCount <= totalCharCount; maxCount += 1) {
    cache.fill(0);
    let standardCount = 0;
    let charCount = 0;
    let left = 0;
    for (let i = 0; i < s.length; i += 1) {
      const cacheIndex = s.charCodeAt(i) - codeA;
      cache[cacheIndex] += 1;
      if (cache[cacheIndex] === k) {
        standardCount += 1;
      }
      if (cache[cacheIndex] === 1) {
        charCount += 1;
      }
      while (charCount > maxCount) {
        const _cacheIndex = s.charCodeAt(left) - codeA;
        cache[_cacheIndex] -= 1;
        left += 1;
        if (cache[_cacheIndex] === k - 1) {
          standardCount -= 1;
        }
        if (!cache[_cacheIndex]) {
          charCount -= 1;
        }
      }
      if (standardCount === charCount && standardCount >= maxCount) {
        max = Math.max(max, i - left + 1);
      }
    }
  }
  return max;
}

console.log(longestSubstring('aaabb', 3) === 3);
console.log(longestSubstring('ababbc', 1) === 6);
console.log(longestSubstring('ababbc', 2) === 5);
